<!--
 *@Date: 2022-12-06 10:13:22
 * @LastEditTime: 2023-02-08 11:41:50
 *
 * @Description:
-->


<template>
    <base-container>
        <view style="padding-bottom:20rpx">
            <view class="search">
                <uni-search-bar style="flex:1" v-model="searchKey" bgColor="#fff" radius="5" placeholder="请输入关键字"
                    clearButton="auto" cancelButton="none" @confirm="search" />
                <uni-icons v-if="(listOperation.qxpz && (listOperation.qxpz.plclLeft || listOperation.qxpz.plclRight))"
                    type="bars" size="24" color="#808080" @tap="openDrawer"></uni-icons>
            </view>
            <checkbox-group @change="checkboxChange">
                <uni-group v-for="(item, index) in sjdxList" :key="index" :title="'第' + (index + 1) + '条记录'" mode="card"
                    top="0">
                    <view v-show="sjdxFields[item1].kjlx !== 'seq'" v-for="(item1, index1) in sjdxLbFields" :key="index1">
                        <view style="display:flex;font-size:28rpx;line-height:48rpx;align-items: center;">
                            <view class="title" v-if="sjdxFields[item1].kjlx !== 'checkbox'">
                                {{ sjdxFields[item1].zdmc }}
                            </view>
                            <view class="info" style="margin-top:-65px" v-if="sjdxFields[item1].kjlx === 'checkbox'">
                                <checkbox style="transform:scale(0.7)" :value="item.id" />
                            </view>
                            <view class="info" style="height:30px" v-else-if="sjdxFields[item1].kjlx === '$buttons'">
                                <button @tap="plcl(key, item2, item)" style="margin-left:4rpx;"
                                    v-for="(item2, key, index2) in getButtons(sjdxFields[item1].kzxxObj.kjkz.btns)"
                                    :key="index2" v-show="index2 < 2" size="mini">{{ item2.content }}</button>
                            </view>
                            <view v-else class="info">
                                <view
                                    v-show="(!bjms) || sjdxFields[item1].kzxxObj.cllxkz && sjdxFields[item1].kzxxObj.cllxkz.select && sjdxFields[item1].kzxxObj.cllxkz.select.disabled && sjdxFields[item1].kzxxObj.cllxkz.select.readonly">
                                    <view v-if="sjdxFields[item1].kjlx === 'ElDatePicker'">
                                        {{ dayjs(item[item1], "YYYYMMDDHHmmss").format("YYYY-MM-DD HH:mm:ss") }}
                                    </view>
                                    <data-image v-else-if="sjdxFields[item1].kjlx === 'MyImage'" v-model="item[item1]" />
                                    <view v-else>
                                        {{ item[item1 + '_mc'] ? item[item1 + '_mc'] : item[item1] }}
                                    </view>
                                </view>
                                <view
                                    v-show="!((!bjms) || sjdxFields[item1].kzxxObj.cllxkz && sjdxFields[item1].kzxxObj.cllxkz.select && sjdxFields[item1].kzxxObj.cllxkz.select.disabled && sjdxFields[item1].kzxxObj.cllxkz.select.readonly)">
                                    <data-page-select :zdlb="sjdxFields[item1].zdzdlb" v-model="item[item1]"
                                        :name="item[item1 + '_mc']"
                                        v-if="sjdxFields[item1].kjlx === '$select' && sjdxFields[item1].zdfy === '1'"></data-page-select>
                                    <data-select class="input-info" v-else-if="sjdxFields[item1].kjlx === '$select'"
                                        v-model="item[item1]" :zdlb="sjdxFields[item1].zdzdlb" />
                                    <data-checkbox v-else-if="sjdxFields[item1].kjlx === '$checkbox'" multiple
                                        v-model="item[item1]" :zdlb="sjdxFields[item1].zdzdlb">
                                    </data-checkbox>
                                    <data-switch v-else-if="sjdxFields[item1].kjlx === '$switch'"
                                        v-model="item[item1]"></data-switch>
                                    <date-picker class="input-info" v-else-if="sjdxFields[item1].kjlx === 'ElDatePicker'"
                                        v-model="item[item1]" />
                                    <data-image v-else-if="sjdxFields[item1].kjlx === 'MyImage'" update
                                        v-model="item[item1]" />
                                    <uni-easyinput v-else class="input-info" type="text" v-model="item[item1]"
                                        :placeholder="'请输入' + sjdxFields[item1].zdmc" />
                                </view>
                            </view>
                        </view>
                        <uni-collapse class="collapse"
                            v-if="sjdxFields[item1].kjlx === '$buttons' && Object.getOwnPropertyNames(getButtons(sjdxFields[item1].kzxxObj.kjkz.btns)).length > 2"
                            accordion>
                            <uni-collapse-item :title="'更多' + sjdxFields[item1].zdmc">
                                <view style="display:flex;flex-wrap: wrap;">
                                    <button style="margin:4rpx;" @tap="plcl(key, item2, item)"
                                        v-for="(item2, key, index2) in getButtons(sjdxFields[item1].kzxxObj.kjkz.btns)"
                                        :key="index2" v-show="index2 > 1" size="mini">
                                        {{ item2.content }}
                                    </button>
                                </view>
                            </uni-collapse-item>
                        </uni-collapse>
                    </view>
                </uni-group>
                <uni-load-more :status=loadMoreStatus></uni-load-more>
            </checkbox-group>
            <view v-show="topShow" @tap="goTop"
                style="position:fixed;bottom:40rpx;right:40rpx;padding:8rpx;background-color:#fff;border-radius:50%;border:1px solid #c8c7cc;color: #999;text-align: center;">
                <uni-icons type="top" size="24" color="#808080"></uni-icons>
            </view>
        </view>
        <uni-drawer ref="showRight" mode="right">
            <scroll-view style="height: 100%;" scroll-y="true">
                <view style="text-align: center;padding:20rpx">列表操作</view>
                <uni-list>
                    <view v-if="listOperation.qxpz">
                        <uni-list-item v-show="bjms" clickable title="保存"
                            @tap="plcl('plbc', { content: '保存', buttonOptions: { clfs: 'plbc', htqqts: true, sfxyxzjl: false } })"></uni-list-item>
                        <uni-list-item clickable @tap="plcl(name, item)"
                            v-show="!((item.content === '编辑模式' && bjms) || (item.content === '取消编辑' && !bjms)) && (useUserStore().userAuth(myData.dxjcxx.sys.authCode + '_' + name) || useUserStore().userAuth(authCodeDefault + '_' + name))"
                            v-for="(item, name, index) in listOperation.qxpz.plclLeft" :key="index"
                            :title="item.content"></uni-list-item>
                        <uni-list-item clickable @tap="plcl(name, item)"
                            v-for="(item, name, index) in listOperation.qxpz.plclRight" :key="index"
                            v-show="useUserStore().userAuth(myData.dxjcxx.sys.authCode + '_' + name) || useUserStore().userAuth(authCodeDefault + '_' + name)"
                            :title="item.content"></uni-list-item>
                    </view>
                    <uni-list-item clickable title="关闭" @tap="closeDrawer"></uni-list-item>
                </uni-list>
            </scroll-view>
        </uni-drawer>
    </base-container>
</template>

<script setup lang="ts">
import { onLoad, onPageScroll, onPullDownRefresh, onReachBottom, onUnload } from '@dcloudio/uni-app';
import { reactive, ref } from 'vue';
import SjdxModelImp from '../model/SjdxModelImp';
import lodash from 'lodash'
import { useUserStore } from '@/stores/modules/user';
import { useDistStore } from '@/stores/modules/dist';
import dayjs from 'dayjs';
import { copyByPathMap, getByPath } from '@/utils/common/common';

const bjms = ref(false)
const checkedList = ref([])
const sjdxModelImp = new SjdxModelImp()
const sjdxList = ref([] as any)
const sjdxListOld = ref([] as any)
const sjdxLbFields = ref([] as any)
const searchKey = ref('')
const sjdxFields = ref({})
const loadMoreStatus = ref('loading')
const cxmrz = ref({})
let authCodeDefault = ''
const myData = reactive({
    dxjcxx: {} as any,
    obj: {} as any
})
const showRight = ref()
const listOperation = ref({} as any)
const page = reactive({
    totalPage: 0,
    pageNumber: 1,
    pageSize: 10,
    listRequired: true,
    totalRequired: true
})
const topShow = ref(false)
const checkboxChange = (e: any) => {
    console.log(e.detail.value)
    checkedList.value = e.detail.value
}
const showPageSelect = (item: any) => {
    console.log(item)
}
onLoad((params: any) => {
    console.log(params)
    Object.keys(params).map(key => {
        let keyList = key.split(".")
        if (keyList[0] === "fields" && keyList[2] === "cxmrz") {
            cxmrz.value[keyList[1]] = params[key]
        }
    })
    const { dm, title, authCode } = params;
    uni.setNavigationBarTitle({
        title: title
    });
    if (authCode) {
        authCodeDefault = authCode
    }
    sjdxModelImp.initSjdx(dm).then((result: any) => {
        sjdxLbFields.value = sjdxModelImp.getSjdxLbFields()
        sjdxFields.value = sjdxModelImp.getSjdxFields()
        listOperation.value = sjdxModelImp.getListOperation()
        myData.dxjcxx = result
        getSjdxList()
    })
    useDistStore().getDictList({ zdlb: 'SYS_SJGL_DXLB' }).then(res => {
        console.log(res.length)
    })

    useDistStore().getDictMc('SYS_SJGL_DXLB', '01').then(res => {
        console.log(res)
    })

    uni.$on('sjdxIndexRefresh', () => {
        searchKey.value = ''
        page.pageNumber = 1
        sjdxList.value = []
        getSjdxList()
    })
})

onUnload(() => {
    uni.$off('sjdxIndexRefresh');
})

onPageScroll(e => {
    if (e.scrollTop > 2000) {
        topShow.value = true
    } else {
        topShow.value = false
    }
})

const getButtons = (item: any) => {
    let obj = {} as { string: { content: '' } }
    Object.keys(item).map(key => {
        if (authCodeDefault && authCodeDefault !== '') {
            if (useUserStore().userAuth(authCodeDefault + '_' + key)) {
                obj[key] = item[key]
            }
        }
        else {
            if (useUserStore().userAuth(myData.dxjcxx.sys.authCode + '_' + key)) {
                obj[key] = item[key]
            }
        }
    })
    return obj
}

const plcl = (cllx: any, btnProps: any, row?: any) => {
    if (cllx === 'pzdx') {
        uni.showToast({
            icon: 'none',
            title: '暂不支持此操作'
        });
        return;
    }
    console.log(cllx, btnProps, row)
    myData.dxjcxx.obj = row
    const buttonOptions = btnProps.buttonOptions;
    const clfs = buttonOptions.clfs || 'htqq';
    let content = btnProps.content;
    let ids = [] as any;
    ids = checkedList.value
    if (row) {
        ids = [row.id];
    }
    if (ids.length === 0 && buttonOptions.sfxyxzjl !== false) {
        uni.showToast({
            icon: 'none',
            title: '请选择要操作的数据'
        });
        return;
    }

    switch (clfs) {
        case "htqq":
            if (buttonOptions.htqqts) {
                uni.showModal({
                    title: '提示',
                    content: `你确定${content}吗？`,
                    success: function (res) {
                        if (res.confirm) {
                            sjdxModelImp.htqq(myData.dxjcxx, cllx, ids, buttonOptions).then(res => {
                                if (res.status) {
                                    setTimeout(() => {
                                        search()
                                    }, 1000)
                                }
                            })
                        } else if (res.cancel) {
                        }
                    }
                });
            } else {
                sjdxModelImp.htqq(myData.dxjcxx, cllx, ids, buttonOptions)
            }
            break
        case "ymcsth":
            if (cllx === 'bjms') {
                bjms.value = true;
                sjdxListOld.value = lodash.cloneDeep(sjdxList.value)
            }
            if (cllx === 'qxbj')
                bjms.value = false;
            break
        case "plbc":
            let editTableData = [] as any
            //比较sjdx修改的部分
            sjdxList.value.map((item: any, index: number) => {
                if (!lodash.isEqual(item, sjdxListOld.value[index])) {
                    let obj = { id: '' }
                    Object.keys(item).map(key => {
                        if (item[key] !== sjdxListOld.value[index][key]) {
                            obj[key] = item[key]
                        }
                    })
                    obj.id = item.id
                    editTableData.push(obj)
                }
            })
            if (buttonOptions.htqqts) {
                uni.showModal({
                    title: '提示',
                    content: `你确定${content}吗？`,
                    success: function (res) {
                        if (res.confirm) {
                            sjdxModelImp.htqq(myData.dxjcxx, cllx, ids, buttonOptions, editTableData).then(res => {
                                bjms.value = false
                            })
                        } else if (res.cancel) {
                        }
                    }
                });
            } else {
                sjdxModelImp.htqq(myData.dxjcxx, cllx, ids, buttonOptions, editTableData)
            }
            break;
        case "tcck":
            let jcxxkz = ""
            let tccllx = cllx
            if (buttonOptions.dxjcxx && buttonOptions.dxjcxx.sys && buttonOptions.dxjcxx.sys.cllx) {
                tccllx = buttonOptions.dxjcxx.sys.cllx
            }
            if (buttonOptions.jcxxqqcskz) {
                copyByPathMap(buttonOptions.dxjcxx, myData, buttonOptions.jcxxqqcskz)
            }
            if (buttonOptions.jcxxkz) {
                Object.keys(buttonOptions.jcxxkz).map(item => {
                    jcxxkz += `&${item}=${getByPath(myData, buttonOptions.jcxxkz[item])}`
                })
            }
            copyByPathMap(myData.dxjcxx, myData, buttonOptions.jcxxkz)
            if (tccllx === 'dxjcxx') {
                uni.navigateTo({ url: `/pages/sjdx/view/detail?dm=${myData.dxjcxx.sjdx.dxdm}&id=${row.id}&title=${content}【${myData.dxjcxx.sjdx.dxmc}】${jcxxkz}` })
            }
            else if (tccllx === 'select') {
                uni.navigateTo({ url: `/pages/sjdx/view/index?dm=${buttonOptions.dxjcxx.sjdx.dxdm}&title=${content}【${myData.dxjcxx.sjdx.dxmc}】${jcxxkz}` })
            }
            else if (tccllx === 'insert') {
                uni.navigateTo({ url: `/pages/sjdx/view/update?dm=${myData.dxjcxx.sjdx.dxdm}&cllx=insert&title=${content}【${myData.dxjcxx.sjdx.dxmc}】${jcxxkz}` })
            }
            else if (tccllx === 'update') {
                uni.navigateTo({ url: `/pages/sjdx/view/update?dm=${myData.dxjcxx.sjdx.dxdm}&cllx=update&id=${row.id}&title=${content}【${myData.dxjcxx.sjdx.dxmc}】${jcxxkz}` })

            } else {
                uni.showToast({
                    icon: 'none',
                    title: '暂不支持此操作'
                });
            }
            break;
        default:
            uni.showToast({
                icon: 'none',
                title: '暂不支持此操作'
            });
    }
    closeDrawer()
}

const goTop = () => {
    uni.pageScrollTo({
        scrollTop: 0,
        duration: 300
    })
}

const closeDrawer = () => {
    showRight.value.close();
}

const openDrawer = () => {
    showRight.value.open();
}

const getSjdxList = () => {
    return new Promise<void>((resolve, reject) => {
        sjdxModelImp.getSjdxList(
            myData.dxjcxx.sys.authCode,
            page,
            { yxx: '1', ...cxmrz.value }, searchKey.value).then((res: any) => {
                res.list.map((item: any) => {
                    item.isChecked = false;
                })
                page.totalPage = res.totalPage;
                if (page.pageNumber === 1) {
                    sjdxList.value = res.list
                } else {
                    page.pageNumber = res.pageNumber;
                    sjdxList.value = sjdxList.value.concat(res.list);
                }
                if (page.totalPage > page.pageNumber) {
                    loadMoreStatus.value = 'more'
                } else {
                    loadMoreStatus.value = 'noMore'
                }
                resolve()
            }).catch(() => {
                reject()
            })
    })
}

const search = () => {
    page.pageNumber = 1
    getSjdxList()
}

const loadMore = () => {
    if (page.totalPage <= page.pageNumber) return
    loadMoreStatus.value = 'loading'
    page.pageNumber = page.pageNumber + 1
    getSjdxList()
}

onReachBottom(() => {
    loadMore()
})
onPullDownRefresh(() => {
    searchKey.value = ''
    page.pageNumber = 1
    sjdxList.value = []
    getSjdxList().then(() => {
        uni.stopPullDownRefresh()
    }).catch(() => {
        uni.stopPullDownRefresh()
    })
})




</script>

<style lang="scss" scoped>
.title {
    width: 168rpx;
    color: $uni-text-color-grey;
}

.search {
    display: flex;
    align-items: center;
    padding-right: 16rpx;
    position: sticky;
    /*  #ifdef H5  */
    top: 44px;
    /*  #endif  */
    /*  #ifndef H5  */
    top: 0px;
    /*  #endif  */

    background-color: #F5F7F8;
    z-index: 99;
    border-top: 1px solid #eee
}

.info {
    flex: 1;
    text-align: right;
    align-items: center;
}

.input-info {
    flex: 1;
    text-align: left;
}

.collapse {
    ::v-deep .uni-collapse-item__title-box {
        padding: 0;
    }

    ::v-deep .uni-collapse-item__title-text {
        line-height: 48rpx;
    }
}
</style>
